<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/10 0010
 * Time: 11:03
 */

// 获取客服类型名称
function get_kefu_type($type) {
    switch ($type) {
        case 'ww' :
            return '阿里旺旺';
            break;
        case 'qq' :
            return 'QQ';
            break;
        default:
            return '';
        break;
    }
}

/**根据id查找顶级类
 *
 */
function scan_pid($id){
    //子级找父级
    $id_get_pid = db('category')->where("id=$id")->find();

    $parent_id = $id_get_pid['pid'];

    //是否顶级，不是则继续找
    if($parent_id != 0) {
        return scan_pid($parent_id);
    } else {
        return $id_get_pid;
    }

}

//获取产品列表分类树
function Ztree($category_id = 0, $is_descendant = true, $is_product = 0) {
    $data = db('category')->select(); // 获取所有分类
    $pids = scan_pid($category_id) ? scan_pid($category_id) : []; // 获取指定分类的所有上级分类

    $descendant = [];
    if ($category_id > 0 && $is_descendant) {
        $cates = get_cates('category', $category_id);  // 取出所有分类的后代元素
        $descendant[] = $category_id;
        foreach ($cates as $v) {
            $descendant[] = $v['id'];  // 将后代元素保存到一个数组
        }
    }

    //树部分
    $ztree = "[{id:0, pId:0, name:'顶级分类', open:true, click:'save_cid(0, $is_product, 0)'},";
    foreach ($data as $v) {
        if (in_array($v['id'], $descendant)) {  // 排除后代元素
            continue;
        }
        if (in_array($v['id'], $pids)) {
            $ztree .= "{id:$v[id], pId:$v[pid], name:'$v[name]', nocheck: true ,open:true, click:'save_cid($v[id], $is_product, $v[level])'},";
        } else {
            $count = db('category')->where("pid = $v[id]")->count();
            if ($count > 0) {
                $ztree .= "{id:$v[id], pId:$v[pid], name:'$v[name]', nocheck: true, click:'save_cid($v[id], $is_product, $v[level])' },";
            } else {
                $ztree .= "{id:$v[id], pId:$v[pid], name:'$v[name]', click:'save_cid($v[id], $is_product, $v[level])'},";
            }
        }
    }
    $ztree = substr($ztree, 0, -1) . "]";
    return  $ztree;
}

//根据pid(上级分类ID)取出后代， 并且给每一代分类定义好级别
function get_cates($table, $pid = 0, $level = 0, $noid = 0)
{
    static $res = [];// static 定义函数内部的全局变量; 当函数内部调用该函数本身时，所得数据需要该定义才能追加保存到同一变量；
    $data = db($table)->where('pid', $pid)->where('id', 'neq', $noid)->select();
    //print_r($data);die;
    foreach($data as $v)
    {
        $v['level'] = $level;	//记录级别
        $res[] = $v;
        get_cates($table, $v['id'], $level+1, $noid);	//函数内部调用该函数本身
    }

    return $res;
}

function is_show($is_show) {
    $show_array = ['不启用', '启用'];
    return $show_array[$is_show];
}

function get_news_category($cate_id) {
    return db('news_category')->where('id', $cate_id)->value('name');
}